//
//  MAKRequest+RAC.m
//  MAKNet
//
//  Created by zwh on 2021/2/19.
//  Copyright © 2021 mark. All rights reserved.
//

#import "MAKRequest+RAC.h"
#import "MAKResponse.h"

@implementation MAKRequest (RAC)

- (RACSignal *)rac_requestData {
    [self stop];
    return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
        [self mak_startWithCompletionBlockWithSuccess:^BOOL(MAKResponse* response) {
            
            BOOL result = NO;
            if(response){
                id obj = [response handle:self];
                if([obj isKindOfClass:NSError.class]){
                    NSError* error = obj;
                    [subscriber sendError:error];
                }else{
                    [subscriber sendNext:obj];
                    [subscriber sendCompleted];
                    result =YES;
                }
            }
            return result;
        } blockFailure:^(__kindof NSError *error) {
            if([self mak_handleError:error]){
                [subscriber sendCompleted];
            }else{
                [subscriber sendError:error];
            }
        }];
        return [RACDisposable disposableWithBlock:^{
            if (!self.isExecuting) {
                [[YTKNetworkAgent sharedAgent] cancelRequest:self];
            }
        }];
    }];
}

@end
